# =============================================================================
# APPENDIX C: INDIVIDUAL COUNTRY PLOTS 
# Generates multi-page PDFs with individual country time series plots
# =============================================================================

# --- PACKAGES ----------------------------------------------------------------
library(dplyr)
library(ggplot2)
library(cowplot)

# --- CONFIGURATION -----------------------------------------------------------
plots_per_page <- 15
ncol_grid      <- 3  # 3 cols → 5 rows per page with 15 plots

# Minimalist grayscale theme for reuse
base_theme <- theme_bw() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
    panel.grid.minor = element_blank()
  )

# --- DATA LOADING ------------------------------------------------------------
data <- read.csv("estimates_independent.csv")

# --- DATA PREPARATION --------------------------------------------------------
# Drop rows missing key plotting fields
data <- data %>%
  filter(!is.na(country_name), !is.na(year), !is.na(dyn.estimates))

# Define plotting bounds
x_min <- max(1946, min(data$year, na.rm = TRUE))
x_max <- min(2023, max(data$year, na.rm = TRUE))

# Prepare country list and pagination
country_list <- sort(unique(data$country_name))
num_pages    <- ceiling(length(country_list) / plots_per_page)

# --- VISUALIZATION -----------------------------------------------------------
# Build and save pages
for (page in seq_len(num_pages)) {
  idx_start <- (page - 1) * plots_per_page + 1
  idx_end   <- min(idx_start + plots_per_page - 1, length(country_list))
  countries <- country_list[idx_start:idx_end]
  
  plot_list <- lapply(countries, function(cty) {
    df <- filter(data, country_name == cty)
    
    ggplot(df, aes(x = year, y = dyn.estimates)) +
      geom_errorbar(aes(ymin = dyn.lo, ymax = dyn.up), 
                    width = 0.1, alpha = 0.6) +
      geom_line(linewidth = 0.4) +
      labs(title = cty, x = "Year", y = "Latent Estimate") +
      scale_x_continuous(limits = c(x_min, x_max), 
                         breaks = seq(x_min, x_max, by = 5)) +
      base_theme
  })
  
  # --- OUTPUT ----------------------------------------------------------------
  pdf_file <- sprintf("plots_page_%d.pdf", page)
  pdf(pdf_file, width = 11, height = 8.5)
  print(plot_grid(plotlist = plot_list, ncol = ncol_grid))
  dev.off()
}
